<!--
 * @Author: your name
 * @Date: 2021-09-15 10:44:50
 * @LastEditTime: 2021-09-15 16:41:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \briup\6-jQuery\day04\5-拖放.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖放</title>
    <style>
        #div1,
        #div2 {
            border: 1px solid green;
            width: 80px;
            height: 80px;
            margin: 10px;
            padding: 10px;
            float: left;
        }
        
        #div1>img {
            border: 1px solid gold;
        }
    </style>
</head>

<body>
    <!-- 拖动事件 -->
    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
        <img id="img" draggable="true" ondragstart="drag(event)" src="./briup.png" alt="图片丢失" height="62">
    </div>
    <!-- 放置事件 -->
    <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">

    </div>
</body>
<script>
    function allowDrop(ev) {
        //preventDefault() 阻止默认事件
        ev.preventDefault();

        function drag(ev) {
            console.log(ev);
            //保存img图片的id
            ev.dataTransfer.setData("Text", ev.target.id);
        }

        function drop(ev) {
            //preventDefault() 阻止默认事件
            ev.preventDefault();
            //在放置事件获取img的id
            var data = ev.dataTransfer.getData("Text");
            //把获取的id追加放到目标事件后面
            ev.target.appendChild(document.getElementById(data));
        }
    }
</script>

</html>